package com.jeff.android.lab.android.ipc;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jeff.android.lab.BaseFragment;
import com.jeff.android.lab.R;
import com.jeff.utils.LogUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author: dingfeng
 * @date: 2020-02-17
 * @since: 1.0.0
 **/
public class MessengerFragment extends BaseFragment {

    @BindView(R.id.tv_send)
    TextView tv_send;

    @BindView(R.id.tv_reply)
    TextView tv_reply;

    private Messenger mMessengerService = null;

    @Override
    protected int getRootLayout() {
        return R.layout.android_fragment_ipc_messenger;
    }

    private Messenger mMessenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String serviceMsg = bundle.getString("server");
            LogUtil.d(TAG, "Data from server:" + serviceMsg);

            tv_reply.setText("服务端返回数据：" + serviceMsg);
        }
    });

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessengerService = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(mContext, MessengerService.class);
        mContext.bindService(intent, connection, Service.BIND_AUTO_CREATE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unbindService(connection);
    }

    @OnClick(R.id.bt_send)
    public void send() {
        if (mMessengerService != null) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            String content = "今天出去玩吗？";
            bundle.putString("client", content);
            message.setData(bundle);
            message.replyTo = mMessenger;

            try {
                mMessengerService.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            tv_send.setText("发送数据到服务端：" + content);
        }
    }

}
